package servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 10:07
 **/
@WebServlet("/downLoad")
public class Download extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.得到文件名filename：通过获取请求参数
        * 2.得到文件的真实路径realpath ：通过servletcontext
        * 3.通过输入流读取文件，输出流写数据
        * 4.以附件的形式下载文件，需要设置响应头
        * response.setHeader("Content-Disposition","attachment";filename="+filename)*/

        String filename=req.getParameter("filename");
        System.out.println(filename);

        ServletContext servletContext=req.getServletContext();
        String realpath=servletContext.getRealPath("/img/"+filename);
        FileInputStream fis=new FileInputStream(realpath);

        resp.setHeader("Contest-disposition","attachment;filename="+filename);
        ServletOutputStream outputStream=resp.getOutputStream();

        byte[] bytes=new byte[1024*2];
        int len=0;
        while((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        fis.close();



    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
